package displayManager;

/*--------------------------------------------------
 * Use a stack to push and pop displayable objects
 *
 * public void pushDisplayable(Displayable)
 * public void popDisplayable()
 * public void home()
 *-------------------------------------------------*/
import javax.microedition.lcdui.*;
import java.util.*;

public class DisplayManager extends Stack {

    private Display display;      // Reference to Display object
    private Displayable mainDisplayable; // Main displayable for MIDlet
    private Alert alStackError;  // Alert for error conditions

    public DisplayManager(Display display, Displayable mainDisplayable) {
        // Only one display object per midlet, this is it
        this.display = display;
        this.mainDisplayable = mainDisplayable;

        // Create an alert displayed when an error occurs
        alStackError = new Alert("Displayable Stack Error");
        alStackError.setTimeout(Alert.FOREVER);  // Modal
    }
    /*--------------------------------------------------
     * Push the current displayable onto stack and set
     * the passed in displayable as active
     *-------------------------------------------------*/

    public void pushDisplayable(Displayable newDisplayable) {
        push(display.getCurrent());
        display.setCurrent(newDisplayable);
    }

    /*--------------------------------------------------
     * Return to the main displayable object of MIDlet
     *-------------------------------------------------*/
    public void home() {
        while (elementCount > 1) {
            pop();
        }
        display.setCurrent(mainDisplayable);
    }

    public void popPop() {
        pop();
        display.setCurrent((Displayable) pop());
    }

    public void Home() {
        while (elementCount > 1) {
            pop();
        }
        display.setCurrent((Displayable) pop());
    }

    public Displayable Home2() {
        while (elementCount > 1) {
            pop();
        }
        return (Displayable) pop();
    }

    public void emptyStack() {
        while (elementCount != 0) {
            pop();
        }
    }
    
    /*--------------------------------------------------
     * Pop displayable from stack and set as active
     *-------------------------------------------------*/

    public void popDisplayable() {
        // If the stack is not empty, pop next displayable
        if (empty() == false) {
            display.setCurrent((Displayable) pop());
        } else // On error show an alert
        // Once acknowldeged, set 'mainDisplayable' as active
        {
            display.setCurrent(alStackError, mainDisplayable);
        }
    }
}
